#!/bin/bash

echo "========================================"
echo "   项目启动脚本"
echo "========================================"
echo ""

echo "[1/3] 检查环境..."

if ! command -v node &> /dev/null; then
    echo "❌ 错误: 未找到 Node.js，请先安装 Node.js"
    exit 1
fi

# 检查 Python（优先使用 python3）
PYTHON_CMD=""
if command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
elif command -v python &> /dev/null; then
    PYTHON_CMD="python"
else
    echo "❌ 错误: 未找到 Python，请先安装 Python"
    exit 1
fi

echo "✅ 环境检查通过！"
echo "   Node.js: $(node --version)"
echo "   Python: $($PYTHON_CMD --version)"
echo ""

echo "[2/3] 启动后端服务..."
echo "正在启动 Flask 后端服务器 (端口 5000)..."
cd backend
$PYTHON_CMD app.py &
BACKEND_PID=$!
cd ..

sleep 3

echo "[3/3] 启动前端服务..."
echo "正在启动前端开发服务器 (端口 8081)..."
cd frontend

# 检查 node_modules 是否存在
if [ ! -d "node_modules" ]; then
    echo "⚠️  前端依赖未安装，正在安装..."
    npm install --legacy-peer-deps
    if [ $? -ne 0 ]; then
        echo "❌ 前端依赖安装失败"
        kill $BACKEND_PID 2>/dev/null
        exit 1
    fi
fi

npm run dev &
FRONTEND_PID=$!
cd ..

echo ""
echo "========================================"
echo "  ✅ 服务启动完成！"
echo "========================================"
echo ""
echo "后端服务: http://localhost:5000 (PID: $BACKEND_PID)"
echo "前端服务: http://localhost:8081 (PID: $FRONTEND_PID)"
echo ""
echo "提示:"
echo "  - 前端会自动打开浏览器"
echo "  - 按 Ctrl+C 停止所有服务"
echo ""

# 等待中断信号
trap "echo ''; echo '正在停止服务...'; kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; echo '✅ 服务已停止'; exit" INT TERM

wait

